package com.hzcx.app.simplechat.ui.chat;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.ui.chat.event.ChatListRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatMessageListRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatSearchImgEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatShareUserEvent;
import com.hzcx.app.simplechat.ui.setting.adapter.ChatSearchImgAdapter;
import com.hzcx.app.simplechat.ui.setting.bean.ChatSearchImgBean;
import com.hzcx.app.simplechat.ui.setting.bean.ChatSearchImgSubBean;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.util.date.DateUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import eason.linyuzai.download.ELoad;
import eason.linyuzai.download.recycle.TaskRecycler;
import eason.linyuzai.download.task.DownloadTask;
import io.reactivex.Observable;
import okhttp3.ResponseBody;

/**
 * 查找图片聊天记录
 */
public class ChatSearchImgActivity extends BaseActivity {

    public static final String INTENT_USERINFO = "INTENT_USERINFO";

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.rv_chat_img)
    RecyclerView rvChatImg;

    private UserInfoBean userInfoBean;
    private EMConversation conversation;
    private List<EMMessage> searchList;

    private String lastTime = "";
    private ChatSearchImgBean searchImgBean;
    private List<ChatSearchImgBean> searchData;

    private ChatSearchImgAdapter searchImgAdapter;
    private boolean isSelect;

    private List<EMMessage> selectList; // 选中的数据
    private int downNum = 0;

    @Override
    public int getLayout() {
        return R.layout.activity_chat_search_img;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        tvTitle.setText("视频及图片");
        tvTitleRight.setText("选择");
        tvTitleRight.setTextColor(getResources().getColor(R.color.color_282F3E));

        userInfoBean = (UserInfoBean) getIntent().getSerializableExtra(INTENT_USERINFO);
        conversation = EMClient.getInstance().chatManager().getConversation(userInfoBean.getHxusername());

        searchData = new ArrayList<>();
        selectList = new ArrayList<>();

        searchImgAdapter = new ChatSearchImgAdapter(searchData);
        rvChatImg.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvChatImg.setAdapter(searchImgAdapter);
    }

    @Override
    public void initData() {
        searchList = new ArrayList<>();
        searchList.addAll(conversation.searchMsgFromDB(EMMessage.Type.IMAGE, System.currentTimeMillis(), conversation.getAllMsgCount(),
                null, EMConversation.EMSearchDirection.UP));

        for (int i = 0; i < searchList.size(); i++) {
            EMMessage message = searchList.get(i);
            lastTime = DateUtil.getMonthDate(message.getMsgTime());
            if (i == 0) {
                searchImgBean = new ChatSearchImgBean();
                searchImgBean.setDate(DateUtil.getMonthDate(message.getMsgTime()));
                searchImgBean.setMsgData(new ArrayList<>());
                searchData.add(0, searchImgBean);
                continue;
            }
            if (lastTime.equals(DateUtil.getMonthDate(searchList.get(i - 1).getMsgTime()))) {
                continue;
            } else {
                searchImgBean = new ChatSearchImgBean();
                searchImgBean.setDate(DateUtil.getMonthDate(message.getMsgTime()));
                searchImgBean.setMsgData(new ArrayList<>());
                searchData.add(0, searchImgBean);
            }
        }

        for (int i = 0; i < searchList.size(); i++) {
            for (int j = 0; j < searchData.size(); j++) {
                if (DateUtil.getMonthDate(searchList.get(i).getMsgTime()).equals(searchData.get(j).getDate())) {
                    searchData.get(j).getMsgData().add(new ChatSearchImgSubBean(searchList.get(i)));
                }
            }
        }

        searchImgAdapter.notifyDataSetChanged();

        // 图片内容点击
        searchImgAdapter.setOnSearchImgListener(new ChatSearchImgAdapter.OnSearchImgListener() {
            @Override
            public void imgOnClick(int headPos, int contentPos) {

            }
        });
    }

    @OnClick({R.id.tv_title_right, R.id.rl_delete, R.id.rl_down, R.id.rl_forward})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_title_right:
                if (isSelect) {
                    tvTitleRight.setText("选择");
                    searchImgAdapter.setTag(0);
                    clearCheckBox();
                } else {
                    tvTitleRight.setText("取消");
                    searchImgAdapter.setTag(1);
                }
                isSelect = !isSelect;
                break;

            case R.id.rl_delete:
                deleteImg();
                break;

            case R.id.rl_down:
                downLoadImg();
                break;

            case R.id.rl_forward: // 转发
                forwardImg();
                break;
        }
    }

    /**
     * 转发图片
     */
    private void forwardImg() {
        if (!isSelect) {
            showError("请选择要操作的图片");
            return;
        }
        selectList.clear();
        selectList.addAll(getSelectList());
        if (selectList.size() <= 0) {
            showError("请选择要操作的图片");
            return;
        }
        startActivity(new Intent(this, ChatShareUserActivity.class)
                .putExtra(ChatShareUserActivity.INTENT_FROM_TAG, 2));
    }

    /**
     * 下载图片
     */
    private void downLoadImg() {
        if (!isSelect) {
            showError("请选择要操作的图片");
            return;
        }
        selectList.clear();
        selectList.addAll(getSelectList());
        if (selectList.size() <= 0) {
            showError("请选择要操作的图片");
            return;
        }
        showLoading();
        downNum = 0;
        for (EMMessage message : selectList) {
            EMImageMessageBody imgBody = (EMImageMessageBody) message.getBody();
            String uri = imgBody.getRemoteUrl();
            //可以当成Http Client
            ELoad eload = new ELoad.Builder(ChatSearchImgActivity.this)
                    .addDownloadTaskListener(new DownloadTask.DownloadTaskListener() {
                        @Override
                        public void onDownloadTaskPrepare(DownloadTask task, Observable<ResponseBody> observable) {

                        }

                        @Override
                        public void onDownloadTaskStart(DownloadTask task) {

                        }

                        @Override
                        public void onDownloadTaskPause(DownloadTask task) {

                        }

                        @Override
                        public void onDownloadTaskResume(DownloadTask task) {

                        }

                        @Override
                        public void onDownloadTaskError(DownloadTask task, Throwable e) {
                            LogUtils.d("下载错误:" + e.getMessage());
                            hideLoading();
                        }

                        @Override
                        public void onDownloadTaskComplete(DownloadTask task) {
                            String path = task.getEntity().getFilePath() + "/" +
                                    task.getEntity().getFileName();
                            LogUtils.d("下载完成：" + path);
                            downNum++;
                            if (downNum >= selectList.size()) {
                                hideLoading();
                                runOnUiThread(() -> {
                                    showError("下载完成");
                                    tvTitleRight.setText("选择");
                                    searchImgAdapter.setTag(0);
                                    clearCheckBox();
                                    isSelect = !isSelect;
                                });
                            }
                        }

                        @Override
                        public void onDownloadTaskCancel(DownloadTask task) {

                        }

                        @Override
                        public void onDownloadTaskReset(DownloadTask task) {

                        }

                        @Override
                        public void onDownloadTaskRecycle(DownloadTask task, TaskRecycler taskRecycler) {

                        }
                    }).build();
            //可以当成一个Request
            DownloadTask task = eload.url(uri).create();
            task.start();
        }
    }

    /**
     * 删除图片
     */
    private void deleteImg() {
        if (!isSelect) {
            showError("请选择要操作的图片");
            return;
        }
        selectList.clear();
        selectList.addAll(getSelectList());
        if (selectList.size() <= 0) {
            showError("请选择要操作的图片");
            return;
        }
        for (EMMessage msg : selectList) {
            conversation.removeMessage(msg.getMsgId());
        }
        EventBus.getDefault().post(new ChatMessageListRefreshEvent());
        for (ChatSearchImgBean bean : searchData) {
            Iterator<ChatSearchImgSubBean> it = bean.getMsgData().iterator();
            while (it.hasNext()) {
                ChatSearchImgSubBean subBean = it.next();
                if (subBean.isSelect()) {
                    it.remove();
                }
            }
        }
        searchImgAdapter.notifyDataSetChanged();
        tvTitleRight.setText("选择");
        searchImgAdapter.setTag(0);
        clearCheckBox();
    }

    /**
     * 重置已选择项
     */
    private void clearCheckBox() {
        for (int i = 0; i < searchData.size(); i++) {
            for (int j = 0; j < searchData.get(i).getMsgData().size(); j++) {
                searchData.get(i).getMsgData().get(j).setSelect(false);
            }
        }
    }

    /**
     * 获取选中的数据
     *
     * @return
     */
    private List<EMMessage> getSelectList() {
        List<EMMessage> messages = new ArrayList<>();
        for (int i = 0; i < searchData.size(); i++) {
            for (int j = 0; j < searchData.get(i).getMsgData().size(); j++) {
                if (searchData.get(i).getMsgData().get(j).isSelect()) {
                    messages.add(searchData.get(i).getMsgData().get(j).getMessage());
                }
            }
        }
        return messages;
    }

    /**
     * 选择好友返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void selectUserResult(ChatShareUserEvent event) {
        if (event.getTag() == 2) {
            showLoading();
            for (EMMessage message : selectList) {
                if (message.direct() == EMMessage.Direct.SEND) {
                    EMImageMessageBody imgBody = (EMImageMessageBody) message.getBody();
                    File file = new File(imgBody.getLocalUri().getPath());
                    if (file.exists()) {
                        ChatUtil.getInstance().sendImgMessage(ChatSearchImgActivity.this,imgBody.getLocalUri().getPath(), event.getBean().getHxusername(),
                                ChatConstant.CHATTYPE_SINGLE, event.getBean().getMember_id(),
                                EmptyUtils.isEmpty(event.getBean().getRemarks_name()) ? event.getBean().getNickname() : event.getBean().getRemarks_name(),
                                null);
                    }
                } else {
                    EMImageMessageBody imgBody = (EMImageMessageBody) message.getBody();
                    String uri = imgBody.getRemoteUrl();
                    //可以当成Http Client
                    ELoad eload = new ELoad.Builder(ChatSearchImgActivity.this)
                            .addDownloadTaskListener(new DownloadTask.DownloadTaskListener() {
                                @Override
                                public void onDownloadTaskPrepare(DownloadTask task, Observable<ResponseBody> observable) {

                                }

                                @Override
                                public void onDownloadTaskStart(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskPause(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskResume(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskError(DownloadTask task, Throwable e) {
                                    LogUtils.d("下载错误:" + e.getMessage());
                                    hideLoading();
                                }

                                @Override
                                public void onDownloadTaskComplete(DownloadTask task) {
                                    String path = task.getEntity().getFilePath() + "/" +
                                            task.getEntity().getFileName();
                                    LogUtils.d("下载完成：" + path);
                                    ChatUtil.getInstance().sendImgMessage(ChatSearchImgActivity.this,path, event.getBean().getHxusername(),
                                            ChatConstant.CHATTYPE_SINGLE, event.getBean().getMember_id(),
                                            EmptyUtils.isEmpty(event.getBean().getRemarks_name()) ? event.getBean().getNickname() : event.getBean().getRemarks_name(),
                                            null);
                                }

                                @Override
                                public void onDownloadTaskCancel(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskReset(DownloadTask task) {

                                }

                                @Override
                                public void onDownloadTaskRecycle(DownloadTask task, TaskRecycler taskRecycler) {

                                }
                            }).build();
                    //可以当成一个Request
                    DownloadTask task = eload.url(uri).create();
                    task.start();
                }
            }
            hideLoading();
            showError("发送成功");
            EventBus.getDefault().post(new ChatListRefreshEvent());
            tvTitleRight.setText("选择");
            searchImgAdapter.setTag(0);
            clearCheckBox();
        }
    }
}
